package com.hectopascal.goalance.service;

import com.hectopascal.goalance.pojo.dto.WorkContentBack;
import com.hectopascal.goalance.repository.WorkContentRepository;
import com.hectopascal.goalance.service.Ipml.IFileDownloadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class FileDownloadService implements IFileDownloadService {
    @Autowired
    WorkContentRepository workContentRepository;

    @Value("${file.upload-dir.documents}") // 在application.properties中配置基础路径
    private String documentsPath; // 例如：/var/www/uploads/
    @Override
    public Resource downloadFile(Integer id) throws MalformedURLException {
        WorkContentBack workContent=workContentRepository.getWorkContentById(id).get();
        if (workContent.getAttachment() == null || workContent.getAttachment().isEmpty()) {
            throw new RuntimeException("No attachment found for this record");
        }
        // 去掉 workContent.getAttachment() 中的 documentsPath 部分
        String relativePath = workContent.getAttachment().replaceFirst(documentsPath + "/", "");
        // 构建完整文件路径并规范化
        Path filePath = Paths.get(documentsPath).resolve(relativePath).normalize();
        // 安全校验：确保路径在基础目录内
        if (!filePath.startsWith(Paths.get(documentsPath).normalize())) {
            throw new SecurityException("Attempted directory traversal attack");
        }
        Resource resource = new UrlResource(filePath.toUri());

        // 3. 检查文件是否存在
        if (!resource.exists() || !resource.isReadable()) {
            throw new RuntimeException("File not found or not readable: " + filePath);
        }

        return resource;
    }
}
